package com.atguigu.shardingjdbcdemo.algorithm;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author zhaojiaxu
 * @date 2021/10/19 16:51
 **/
@Component
@Slf4j
public class PreciseModuloAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * 选表
     */
    @Override
    public String doSharding(final Collection<String> tableNames, final PreciseShardingValue<Long> shardingValue) {
        log.info("tableNames:{}", JSON.toJSONString(tableNames));
        log.info("shardingValue:{}", JSON.toJSONString(shardingValue));

        String tableName = "";

        if ("course".equalsIgnoreCase(shardingValue.getLogicTableName())) {
            //分表逻辑是 cid如果是偶数我们就分到 course_1这张表 如果cid是奇数我们就分到 course_2这张表
            if ("0".equals(Long.toString(shardingValue.getValue() % 2))) {
                String shardingTable = shardingValue.getLogicTableName() + "_1";
                tableName = shardingTable;
            } else if ("1".equals(Long.toString(shardingValue.getValue() % 2))) {
                String shardingTable = shardingValue.getLogicTableName() + "_2";
                tableName = shardingTable;
            }
        }
        // 其他表分表逻辑
//        if ("t_user".equalsIgnoreCase(shardingValue.getLogicTableName()) ||
//                "t_order_item".equalsIgnoreCase(shardingValue.getLogicTableName())) {
//            for (String each : tableNames) {
//                if (each.endsWith(shardingValue.getValue() % tableNames.size() + "")) {
//                    tableName = each;
//                    break;
//                }
//            }
//        }

        log.info("tableName:{}", tableName);
        if (StringUtils.isNotEmpty(tableName)) {
            return tableName;
        }

        throw new UnsupportedOperationException();
    }
}

